//! # 工具函数和辅助类
//!
//! 提供认证服务所需的各种工具函数和辅助类。

// 重新导出 rustcloud-security 中的工具
pub use rustcloud_security::utils::*;

// 可以在这里添加 rustcloud-auth 特有的工具函数

/// 时间工具
pub struct TimeUtils;

impl TimeUtils {
    /// 获取当前时间戳（秒）
    pub fn now_timestamp() -> u64 {
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs()
    }

    /// 检查时间戳是否过期
    pub fn is_expired(timestamp: u64, ttl_seconds: u64) -> bool {
        let now = Self::now_timestamp();
        timestamp + ttl_seconds < now
    }

    /// 格式化时间戳为可读字符串
    pub fn format_timestamp(timestamp: u64) -> String {
        let datetime = chrono::DateTime::from_timestamp(timestamp as i64, 0)
            .unwrap_or_default();
        datetime.format("%Y-%m-%d %H:%M:%S UTC").to_string()
    }
}

/// 字符串工具
pub struct StringUtils;

impl StringUtils {
    /// 生成随机字符串
    pub fn random_string(length: usize) -> String {
        use rand::Rng;
        const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        let mut rng = rand::thread_rng();
        
        (0..length)
            .map(|_| {
                let idx = rng.gen_range(0..CHARSET.len());
                CHARSET[idx] as char
            })
            .collect()
    }

    /// 清理和规范化用户名
    pub fn normalize_username(username: &str) -> String {
        username.trim().to_lowercase()
    }

    /// 掩码敏感信息
    pub fn mask_sensitive(input: &str, visible_chars: usize) -> String {
        if input.len() <= visible_chars * 2 {
            "*".repeat(input.len())
        } else {
            let start = &input[..visible_chars];
            let end = &input[input.len() - visible_chars..];
            let middle = "*".repeat(input.len() - visible_chars * 2);
            format!("{}{}{}", start, middle, end)
        }
    }
}

/// 网络工具
pub struct NetworkUtils;

impl NetworkUtils {
    /// 验证IP地址格式
    pub fn is_valid_ip(ip: &str) -> bool {
        ip.parse::<std::net::IpAddr>().is_ok()
    }

    /// 提取真实客户端IP
    #[cfg(feature = "axum-integration")]
    pub fn extract_client_ip(headers: &axum::http::HeaderMap) -> Option<String> {
        let ip_headers = ["x-forwarded-for", "x-real-ip", "x-client-ip"];

        for header_name in &ip_headers {
            if let Some(header_value) = headers.get(header_name) {
                if let Ok(value_str) = header_value.to_str() {
                    let ip = value_str.split(',').next().unwrap_or("").trim();
                    if Self::is_valid_ip(ip) {
                        return Some(ip.to_string());
                    }
                }
            }
        }
        None
    }

    /// 检查是否为私有IP地址
    pub fn is_private_ip(ip: &str) -> bool {
        if let Ok(addr) = ip.parse::<std::net::IpAddr>() {
            match addr {
                std::net::IpAddr::V4(ipv4) => {
                    let octets = ipv4.octets();
                    octets[0] == 10 || 
                    (octets[0] == 172 && (16..=31).contains(&octets[1])) ||
                    (octets[0] == 192 && octets[1] == 168) ||
                    octets[0] == 127
                }
                std::net::IpAddr::V6(ipv6) => {
                    ipv6 == std::net::Ipv6Addr::LOCALHOST ||
                    (ipv6.octets()[0] & 0xfe) == 0xfc
                }
            }
        } else {
            false
        }
    }
}